﻿using Dolany.UtilityTool;
using JetBrains.Annotations;
using Missbot.Core.Base;
using Missbot.Core.Cache;
using Missbot.Model.MsgCmds.Notes;
using Missbot.Model.MsgInfos;
using Newtonsoft.Json;

namespace Missbot.Core.Channels
{
    /// <summary>
    /// 嘟文频道
    /// </summary>
    [UsedImplicitly]
    public class NoteChannel : IMsgChannel
    {
        public override string Name => "note";
        public override ChannelType BindingType => ChannelType.Note;
        public override string ChannelFlag => "note";

        protected override void Send(OutboxDTO dto)
        {
            MsgSender.PushMsg(dto.FileIDs.IsNullOrEmpty()
                                  ? new CreateNoteCmd { ReplyId = dto.SourceID, Text = dto.Text }
                                  : new CreateNoteWithFileCmd { ReplyId = dto.SourceID, Text = dto.Text, FileIDs = dto.FileIDs });
        }

        protected override InboxSession ParseDataImpl(string msg)
        {
            var note = JsonConvert.DeserializeObject<NoteInfo>(msg);
            if (note?.Body == null)
            {
                return null;
            }

            var body = note.Body.Body;
            if (body.User.IsLocalUser && note.Body.ID == "global")
            {
                return null;
            }

            return new InboxSession
            {
                User = body.User,
                Text = body.Text,
                Files = body.Files,
                Channel = this,
                SourceID = body.ID,
                Group = new InstanceGroup { ID = body.User.Host },
                Tags = body.Tags
            };
        }
    }
}